package com.mifengs.mall.ui.login;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mifengs.commonbase.util.NetWorkUtils;
import com.mifengs.mall.Constant;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.di.component.DaggerRetrievePasswordComponent;
import com.mifengs.mall.di.module.RetrievePasswordModule;
import com.mifengs.mall.util.PwdCheckUtil;
import com.mifengs.mall.util.Tools;
import com.mifengs.mall.widget.VerifyCodeView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RetrievePasswordActivity extends BaseActivity<RetrievePasswordPresent> implements RetrievePasswordContract.View {
    @BindView(R.id.et_iphone)
    EditText et_phone_num;
    @BindView(R.id.et_code)
    EditText et_vrifi_code;
    @BindView(R.id.et_new_password)
    EditText et_new_pw;
    @BindView(R.id.et_sure_password)
    EditText et_sure_pw;
    @BindView(R.id.tv_send_code)
    TextView tv_send_code;
    @BindView(R.id.tv_code)
    TextView show_time;
    @BindView(R.id.btn_find_pw)
    Button btn_find_pw;
    @BindView(R.id.tv_title)
    TextView tv_top_center_title;
    /*@Bind(R.id.ll_back)
    LinearLayout ll_back;*/
    @BindView(R.id.tv_pw_diff)
    TextView tv_shoe_err;
    @BindView(R.id.rl_pw_notice)
    LinearLayout rl_notice_show;
    @BindView(R.id.iv_new_pw)
    ImageView imageView_new_pw;
    @BindView(R.id.iv_sure_pw)
    ImageView iv_sure_pw;
    @BindView(R.id.iv_phone_del)
    ImageView iv_phone_del;
    @BindView(R.id.et_verity_code)
    EditText etVerityCode;
    @BindView(R.id.btn_photo_code)
    VerifyCodeView mPhotoCodeWebView;
    private SendCodeTime sendCodeTime;
    private long showTime = 60000;
    private String sendCode;
    private boolean new_pw_isOpen = true;
    private boolean sure_pw_isOpen = true;
    private SendCodeThread codeThread;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    rl_notice_show.setVisibility(View.INVISIBLE);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrieve_password);
        setStatusColorAndMode(R.color.white, true);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        tv_top_center_title.setText(getResources().getString(R.string.find_pw));
        sendCode = tv_send_code.getText().toString();
        sendCodeTime = new SendCodeTime(showTime, 1000);
        et_phone_num.setTextColor(getResources().getColor(R.color.white));
        et_new_pw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
        et_sure_pw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
        setEditTextPassWordShowStyle(et_new_pw);
        setEditTextPassWordShowStyle(et_sure_pw);
        et_phone_num.addTextChangedListener(phoneWatcher);
        et_vrifi_code.addTextChangedListener(textWatcher);
        et_new_pw.addTextChangedListener(textWatcher);
        et_sure_pw.addTextChangedListener(textWatcher);
        etVerityCode.addTextChangedListener(textWatcher);
        mPhotoCodeWebView.loadUrl(Constant.PHONE_CODE);
        mPhotoCodeWebView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mPhotoCodeWebView.reload();
                return false;
            }
        });
    }

    @OnClick(R.id.btn_photo_code)
    public void onViewClicked() {
    }

    class SendCodeThread extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Message msg = new Message();
            msg.what = 1;
            mHandler.sendMessage(msg);
        }
    }

    @OnClick({R.id.btn_find_pw, R.id.tv_send_code, R.id.ll_back, R.id.iv_phone_del, R.id.iv_new_pw, R.id.iv_sure_pw})
    public void onClik(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_send_code:
                if (isCheckPhone()) {
                    if ("获取验证码".equals(tv_send_code.getText().toString())) {
                        mPresenter.sendVerificationCode();
                    }
                }
                break;

            case R.id.btn_find_pw:
                if (isVerification()) mPresenter.retrievePW();
                break;
            case R.id.iv_new_pw:
                if (new_pw_isOpen) {
                    imageView_new_pw.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_eyes_open));
                    et_new_pw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    et_new_pw.setSelection(getNewPasswodrd().length());
                    new_pw_isOpen = !new_pw_isOpen;
                } else {
                    imageView_new_pw.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_eyes_close));
                    setEditTextPassWordShowStyle(et_new_pw);
                    et_new_pw.setSelection(getNewPasswodrd().length());
                    new_pw_isOpen = !new_pw_isOpen;
                }
                break;
            case R.id.iv_sure_pw:
                if (sure_pw_isOpen) {
                    iv_sure_pw.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_eyes_open));
                    et_sure_pw.setSelection(getSurePassword().length());
                    et_sure_pw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    sure_pw_isOpen = !sure_pw_isOpen;
                } else {
                    iv_sure_pw.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_eyes_close));
                    setEditTextPassWordShowStyle(et_sure_pw);
                    et_sure_pw.setSelection(getSurePassword().length());
                    sure_pw_isOpen = !sure_pw_isOpen;
                }
                break;
            case R.id.iv_phone_del:
                et_phone_num.setText("");
                iv_phone_del.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void initInjector() {
        DaggerRetrievePasswordComponent.builder()
                .retrievePasswordModule(new RetrievePasswordModule(this))
                .build()
                .inject(this);
    }

    private boolean isCheckPhone() {
        if (TextUtils.isEmpty(getPhone())) {
            showErrorInfo("请输入手机号码");
            return false;
        } else if (getPhone().length() != 11) {
            showErrorInfo("手机号码输入错误");
            return false;
        } else if (!Tools.checkCellphone(getPhone())) {
            showErrorInfo("请输入正确手机号码");
            return false;
        } else if (TextUtils.isEmpty(getPhotoCode())) {
            showErrorInfo("请输入图片验证码");
            return false;
        } else if (!NetWorkUtils.isNetworkAvailable(MallApplication.getInstance())) {
            showErrorInfo("暂无网络,请确认网络连接");
            return false;
        }
        return true;
    }


    private void showErrorInfo(String errInfo) {
        rl_notice_show.setVisibility(View.VISIBLE);
        tv_shoe_err.setText(errInfo);
        codeThread = new SendCodeThread();
        codeThread.start();
    }

    @Override
    public boolean isVerification() {
        String phone = getPhone();
        String code = getVerificationCode();
        String newPW = getNewPasswodrd();
        String surePW = getSurePassword();
        if (TextUtils.isEmpty(phone)) {
            showErrorInfo("请输入手机号");
            return false;
        } else if (phone.length() != 11) {
            showErrorInfo("手机号码输入错误");
            return false;
        } else if (TextUtils.isEmpty(code)) {
            showErrorInfo("请输入验证码");
            return false;
        } else if (TextUtils.isEmpty(newPW)) {
            showErrorInfo("请输入新密码");
            return false;
        } else if (newPW.length() < 6) {
            showErrorInfo("密码的长度为6-16位");
            return false;
        } else if (newPW.length() > 16) {
            showErrorInfo("密码的长度为6-16位");
            return false;
        } else if (!PwdCheckUtil.isContainAll(newPW)) {
            showErrorInfo("必须同时包含字母+数字的组合");
            return false;
        } else if (TextUtils.isEmpty(surePW)) {
            showErrorInfo("请输入确认密码");
            return false;
        } else if (!newPW.equals(surePW)) {
            showErrorInfo("请确认新密码和确认密码一致");
            return false;
        }
        return true;
    }

    private void setSubmitFalseEnable() {
        btn_find_pw.setEnabled(false);
        btn_find_pw.setBackground(getResources().getDrawable(R.drawable.btn_unselected_show));
    }

    private void setSubmtEnable() {
        btn_find_pw.setEnabled(true);
        btn_find_pw.setBackground(getResources().getDrawable(R.drawable.btn_selected_show));
    }


    @Override
    public String getNewPasswodrd() {
        return TextUtils.isEmpty(et_new_pw.getText().toString()) ? et_new_pw.getText().toString() : et_new_pw.getText().toString().trim();
    }

    @Override
    public String getSurePassword() {
        return TextUtils.isEmpty(et_sure_pw.getText().toString()) ? et_sure_pw.getText().toString() : et_sure_pw.getText().toString().trim();
    }

    @Override
    public void smsSuccess() {
        tv_send_code.setVisibility(View.GONE);
        sendCodeTime.start();
    }

    @Override
    public String getPhone() {
        return TextUtils.isEmpty(et_phone_num.getText().toString()) ? et_phone_num.getText().toString() : et_phone_num.getText().toString().trim();
    }

    @Override
    public String getPhotoCode() {
        return TextUtils.isEmpty(etVerityCode.getText().toString()) ? etVerityCode.getText().toString() : etVerityCode.getText().toString().trim();
    }

    @Override
    public String getVerificationCode() {
        return TextUtils.isEmpty(et_vrifi_code.getText().toString()) ? et_vrifi_code.getText().toString() : et_vrifi_code.getText().toString().trim();
    }

    class SendCodeTime extends CountDownTimer {

        public SendCodeTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            show_time.setVisibility(View.VISIBLE);
            show_time.setText("获取验证码" + "\n" + millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {
            tv_send_code.setVisibility(View.VISIBLE);
            show_time.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sendCodeTime != null) {
            sendCodeTime.cancel();
        }
        if (codeThread != null && codeThread.isAlive()) {
            codeThread.interrupt();
        }
    }

    TextWatcher phoneWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            iv_phone_del.setVisibility(View.GONE);
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String phone = getPhone();
            String newPw = getNewPasswodrd();
            String surePw = getSurePassword();
            String code = getVerificationCode();
            String phoneCode = getPhotoCode();
            if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(code) || TextUtils.isEmpty(newPw) || TextUtils.isEmpty(surePw) || TextUtils.isEmpty(phoneCode)) {
                setSubmitFalseEnable();
            } else {
                setSubmtEnable();
            }
            iv_phone_del.setVisibility(View.VISIBLE);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String phone = getPhone();
            String newPw = getNewPasswodrd();
            String surePw = getSurePassword();
            String code = getVerificationCode();
            String phoneCode = getPhotoCode();
            if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(code) || TextUtils.isEmpty(newPw) || TextUtils.isEmpty(surePw) || TextUtils.isEmpty(phoneCode)) {
                setSubmitFalseEnable();
            } else {
                setSubmtEnable();
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


    public void setEditTextPassWordShowStyle(EditText et) {
        et.setTransformationMethod(new PasswordCharSequenceStyle());
    }

    public class PasswordCharSequenceStyle extends PasswordTransformationMethod {
        @Override
        public CharSequence getTransformation(CharSequence source, View view) {
            return new PasswordCharSequence(source);
        }

        private class PasswordCharSequence implements CharSequence {
            private CharSequence mSource;

            public PasswordCharSequence(CharSequence source) {
                mSource = source;
            }

            public char charAt(int index) {
                return '*';
            }

            public int length() {
                return mSource.length();
            }

            public CharSequence subSequence(int start, int end) {
                return mSource.subSequence(start, end);
            }
        }
    }
}
